import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';

class KeyboardExample extends StatefulWidget {
  KeyboardExample({Key? key}) : super(key: key);

  @override
  _KeyboardExampleState createState() => _KeyboardExampleState();
}

class _KeyboardExampleState extends State<KeyboardExample>
    with WidgetsBindingObserver {
  ScrollController _controller = ScrollController();
  bool showToTopBtn = true; //是否显示“返回到顶部”按钮
  double textHeight = 50;
  GlobalKey _bodyWidget = GlobalKey();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //初始化
    WidgetsBinding.instance!.addObserver(this);

    _controller.addListener(() {
      // print(_controller.offset); //打印滚动位置

      if (_controller.offset < 100 && showToTopBtn) {
        setState(() {
          showToTopBtn = false;
        });
      } else if (_controller.offset >= 100 && showToTopBtn == false) {
        setState(() {
          showToTopBtn = true;
        });
      }
    });
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    WidgetsBinding.instance!.addPostFrameCallback((_) {
      final RenderBox renderbox =
          _bodyWidget.currentContext!.findRenderObject() as RenderBox;
      // print(renderbox.size);
      setState(() {
        if (MediaQuery.of(context).viewInsets.bottom == 0) {
          //关闭键盘
          // print(window.viewInsets.bottom);
          // print(window.devicePixelRatio);
        } else {
          //显示键盘
          _controller.animateTo(_controller.position.maxScrollExtent,
              duration: Duration(milliseconds: 300), curve: Curves.ease);
          setState(() {
            textHeight = 50.0;
          });
          // print(window.viewInsets.bottom);
          // print(window.devicePixelRatio);
        }
      });
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    //销毁
    WidgetsBinding.instance!.removeObserver(this);
    _controller.dispose();
    super.dispose();
  }

  double otherHeight = 190.0;
  int itemCount = 10;
  //ListView滚动的最大值估算。可以直接在SDK的framework源码中打印调试。
  double _extrapolateMaxScrollOffset(
    int firstIndex,
    int lastIndex,
    double leadingScrollOffset,
    double trailingScrollOffset,
    int childCount,
  ) {
    if (lastIndex == childCount - 1) return trailingScrollOffset;
    final int reifiedCount = lastIndex - firstIndex + 1;
    //算出平均值
    final double averageExtent =
        (trailingScrollOffset - leadingScrollOffset) / reifiedCount;
    //加上剩余估计值
    final int remainingCount = childCount - lastIndex - 1;
    return trailingScrollOffset + averageExtent * remainingCount;
  }

  @override
  Widget build(BuildContext context) {
    double bodyH = MediaQuery.of(context).size.height - otherHeight;
    return SafeArea(
        top: false,
        child: Scaffold(
          floatingActionButton: !showToTopBtn
              ? null
              : FloatingActionButton(
                  child: Icon(Icons.arrow_upward),
                  onPressed: () {
                    // print(_controller.position.maxScrollExtent);
                    // print(bodyH + _controller.position.maxScrollExtent);
                    // print((MediaQuery.of(context).padding));
                    //返回到顶部时执行动画
                    // _controller.animateTo(
                    //   _controller.position.maxScrollExtent,
                    //   duration: Duration(milliseconds: 200),
                    //   curve: Curves.ease,
                    // );
                    // setState(() {
                    //   itemCount = 11;
                    // });
                    // SchedulerBinding.instance!.addPostFrameCallback((_) {
                    //   WidgetsBinding.instance!.addPostFrameCallback((_) {
                    //     print(bodyH + _controller.position.maxScrollExtent);
                    //   });
                    // });
                  }),
          appBar: AppBar(title: Text('键盘')),
          bottomSheet: AnimatedContainer(
              duration: Duration(milliseconds: 200),
              color: Colors.green,
              height: textHeight,
              child: TextField(
                decoration: InputDecoration(
                  hintText: '请输入',
                  suffixIcon: IconButton(
                      onPressed: () {
                        FocusScope.of(context).requestFocus(FocusNode());
                        setState(() {
                          textHeight = 200.0;
                        });
                      },
                      icon: Icon(Icons.close)),
                  border: OutlineInputBorder(
                    ///设置边框四个角的弧度
                    borderRadius: BorderRadius.all(Radius.circular(10)),

                    ///用来配置边框的样式
                    borderSide: BorderSide(
                      ///设置边框的颜色
                      color: Colors.red,

                      ///设置边框的粗细
                      width: 2.0,
                    ),
                  ),
                ),
              )),
          body: Container(
            key: _bodyWidget,
            // height: bodyH,
            padding: EdgeInsets.only(bottom: 50),
            color: Colors.blue,
            child: Scrollbar(
                controller: _controller,
                child: NotificationListener(
                    onNotification: (ScrollNotification notification) {
                      double progress = notification.metrics.pixels /
                          notification.metrics.maxScrollExtent;
                      // print(notification.metrics.maxScrollExtent);
                      // print(notification.metrics.extentInside);
                      return false;
                      //return true; //放开此行注释后，进度条将失效
                    },
                    child: Stack(
                      children: [
                        ListView.builder(
                            itemCount: itemCount,
                            controller: _controller,
                            itemBuilder: (_, index) {
                              return ItemCOntainer(
                                index: index,
                              );
                            })
                      ],
                    ))),
          ),
        ));
  }
}

class ItemCOntainer extends StatelessWidget {
  final index;
  const ItemCOntainer({Key? key, this.index}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    SchedulerBinding.instance!.addPostFrameCallback((_) {
      // try {
      //   if (context != null && context.findRenderObject != null) {
      //     final RenderBox? box = (context.findRenderObject() as RenderBox);
      //   }
      // } catch (err) {
      //   print(err);
      // }
    });

    if (index == 3) {
      return Column(children: [Text('发货地'), Text('发货地')]);
    }
    if (index == 5) {
      return Column(children: [
        Image.network('https://workyd.com/image/yhesj_xcs/placeHolder_r.png'),
        Text('发货地发哈里斯大发粉红色的会计法哈罗份上了戴假发还来得及返回撒垃圾袋发货会发生肯德基')
      ]);
    }
    return Container(
      color: Colors.red,
      height: 200,
      child: Text(index.toString()),
    );
  }
}
